/*
 * @Description: 基于axios异步请求工具
 * @Author: yangjiecan
 * @Date: 2020-04-17 10:44:59
 * @LastEditTime: 2020-05-11 17:57:59
 * @LastEditors: yangjiecan
 */
import axios from 'axios'
import session from './session'
import baseConfig from './config'
import aes from './aes'
import main from '../main'
import Qs from 'qs'
const baseUrl = process.env.VUE_APP_URL
const isAes = JSON.parse(process.env.VUE_APP_AES)// 是否开启aes加密
const baseEnv = process.env.NODE_ENV
class AjaxRequest {
  constructor () {
      this.baseEnv = baseEnv
      this.baseURL = baseUrl // 配置默认路径
  }

  configInterceptors (instance, url) {
      // 配置请求拦截
      instance.interceptors.request.use((config) => {
          return config
      })
      // 配置响应拦截
      instance.interceptors.response.use(res => {
        console.log('响应解密前--', res, 'isAes---', isAes)
        isAes && (res.data = JSON.parse(aes.Decrypt(res.data)))
        console.log('解密返回---', res)
        switch (res.data.code) {
            case 401:
                session.clearAll()
                main.$router.push('/login')
                break
            default:
                break
        }
          if (res.status !== 200) {
              return Promise.reject(res)
          } else {
              return res.data
          }
      }, (error) => {
        // 处理响应失败
        if (error.message.includes('timeout')) {
            main.$message.error('网络超时，请联系管理员!')
            return Promise.reject(error)
        }
        return Promise.reject(error)
      })
  }

  request (config) {
      // 创建一个axios实例
      const instance = axios.create()
      if (this.baseEnv !== 'local') {
        axios.defaults.timeout = 10000
      }
      // 添加请求头
      instance.defaults.headers.common.Authorization = baseConfig().headers.Authorization
      instance.defaults.headers.common['Accept-Language'] = 'zh-CN'
      let item = config.data ? 'data' : 'params'
      console.log('加密前----', config)
      config = { baseURL: this.baseURL, ...config }
      if (isAes) { // 入参加密
        if (config.isForm) { // 表单formData数据提交
          config[item] = Qs.stringify(
            { queryString: aes.Encrypt(config[item]) }
          )
        } else {
          config[item] && (config[item] = { queryString: aes.Encrypt(config[item]) })
        }
        console.log('加密后----', config)
      } else {
        if (config.isForm) {
          config[item] = Qs.stringify(config[item])
        }
      }
      if (config.url !== '/auth/logout') {
        this.configInterceptors(instance, config.url)
      }
      return instance(config)
  }
}
export default new AjaxRequest()
